from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from models import User, db
from utils.storage import upload_to_s3
import re

profile_bp = Blueprint('profile', __name__)

@profile_bp.route('/api/profile', methods=['PUT'])
@jwt_required()
def update_profile():
    user_id = get_jwt_identity()
    user = User.query.get(user_id)
    data = request.json
    # 更新字段
    if 'nickname' in data:
        user.nickname = data['nickname'].strip()
    if 'gender' in data and data['gender'] in ['男', '女', '非二元']:
        user.gender = data['gender']
    db.session.commit()
    return jsonify(code=200, msg='保存成功')

@profile_bp.route('/api/upload_avatar', methods=['POST'])
@jwt_required()
def upload_avatar():
    user_id = get_jwt_identity()
    file = request.files.get('avatar')
    # 文件校验
    if not file or not allowed_file(file.filename):
        return jsonify(code=400, msg='仅支持JPG/PNG格式'), 400
    # 上传至S3
    filename = f"{user_id}_{int(time.time())}.{file.filename.split('.')[-1]}"
    url = upload_to_s3(file, filename)
    # 更新用户记录
    user = User.query.get(user_id)
    user.avatar_url = url
    db.session.commit()
    return jsonify(code=200, data={'avatar_url': url})